import { useEffect, useState, useCallback } from 'react';
import { SwapOutlined } from '@ant-design/icons';
import { message, Popover, Select, Empty } from 'antd';
import { Button, Pagination, Row, Col, Modal, Input, Spin } from 'antd';
import dayjs from 'dayjs';
import debounce from 'lodash.debounce';
import { questionListInt, questionEdit } from '@/api/testProblem';
import './index.scss';
const { TextArea } = Input;
const TestProblem = props => {
    // 编辑状态
    const [isEditFlag, setEditFlag] = useState(false);
    // 页面的Loading状态
    const [loading, setLoading] = useState(false);
    // 页面左侧的Loading状态
    const [leftLoading, setLeftLoading] = useState(false);
    // 确认按钮的loading状态
    const [confirmLoading, setConfirmLoading] = useState(false);
    // 当前点击的左侧的对象
    const [currentLeft, setCurrentLeft] = useState({
        name: 'Self-Awareness',
        index: 0,
        active: true,
        eqSkillType: 'SELF_AWARENESS',
    });
    /**
     * 调用接口，获取右边数据
     * @param eqSkillType 是调用getQuestionType这个方法传过来的参数
     */
    const getQuestionType = async eqSkillType => {
        const params = {
            eqSkillType: eqSkillType || 'SELF_AWARENESS',
        };
        setLoading(true);
        questionListInt(params).then((res: any) => {
            setLoading(false);
            if (res) {
                const data = res.map((item: any, index: number) => {
                    item.placeholder = `Enter the test question ${index * 1 + 1}`;
                    item.questionTextValue = item.question;
                    return {
                        ...item,
                        disabled: true,
                    };
                });
                setQuestionList(data);
            } else {
                setQuestionList([]);
            }
        });
    };
    useEffect(() => {
        // 一进来，默认调用接口，获取SELF_AWARENESS的数据
        getQuestionType('SELF_AWARENESS');
    }, []);
    // 正序还是倒叙改变事件
    const answerScoreAscChange = (obj: any) => {
        const updatedData = questionList.map((item: any, index: number) => {
            if (item.questionId === obj.questionId) {
                return { ...item, answerScoreAsc: !item.answerScoreAsc };
            }
            return item;
        });
        setQuestionList(updatedData);
    };
    /**
     * 改变此页面是否是编辑状态
     */
    const editChange = () => {
        const flag = !isEditFlag;
        // 将问题列表的输入框设置为禁用，不是edit的时候就禁用
        const updatedList = questionList.map(item => {
            return { ...item, disabled: !flag };
        });
        setQuestionList(updatedList);
        setEditFlag(flag);
    };

    /**
     * 调用接口，保存数据
     * @param eqSkillType
     */
    const confirmChange = async () => {
        setLoading(true);
        setConfirmLoading(true);
        const list: any = [];
        questionList.map(item => {
            const obj = {
                questionId: item.questionId,
                answerScoreAsc: item.answerScoreAsc,
                question: item.questionTextValue,
            };
            list.push(obj);
        });
        const params = list;
        questionEdit(params).then(res => {
            setLoading(false);
            setConfirmLoading(false);
            // 调用此方法是将状态设置为不是编辑的状态
            editChange();
            // 重新调用问题列表，刷新问题列表
            getQuestionType(currentLeft.eqSkillType || 'SELF_AWARENESS');
        });
    };
    // 右侧的问题列表
    const [questionList, setQuestionList] = useState<
        {
            question: string;
            index: number;
            questionTextValue: string;
            placeholder: string;
            disabled: boolean;
            answerScoreAsc: boolean;
            questionId: string;
            eqSkillType: [];
        }[]
    >([]); // 这里表示是，默认是一个空的数据，数组中的对象类型为以上几种，useState后面的<>尖括号里面写数据的类型，()圆括号里面表示默认数据，这里给的是一个[]空数组，所以，就是默认空数组
    // 输入框改变事件
    const changeTextValue = (value: string, index: number) => {
        const updatedList = questionList.map((item, i) => {
            if (i === index) {
                return { ...item, questionTextValue: value };
            }
            return item;
        });
        setQuestionList(updatedList);
    };
    // 题目列表以及题目切换
    const leftListDefault = [
        {
            name: 'Self-Awareness',
            index: 0,
            active: true,
            eqSkillType: 'SELF_AWARENESS',
        },
        {
            name: 'Self-Regulation',
            index: 1,
            active: false,
            eqSkillType: 'SELF_REGULATION',
        },
        {
            name: 'Social Awareness',
            index: 2,
            active: false,
            eqSkillType: 'SOCIAL_AWARENESS',
        },
        {
            name: 'Social Skill',
            index: 3,
            active: false,
            eqSkillType: 'SOCIAL_SKILL',
        },
    ];
    // 左侧的列表
    const [leftTitle, setLeftTitle] = useState<
        {
            name: string;
            index: number;
            active: boolean;
            eqSkillType: string;
        }[]
    >(leftListDefault); // 这里表示是，默认是leftListDefault数组中的数据，数组中的对象类型为以上几种
    // 点击左侧的列表
    const clickItem = (item: { name: string; index: number; active: boolean; eqSkillType: string }) => {
        getQuestionType(item.eqSkillType);
        setCurrentLeft(item);
        // 创建一个新的数组updatedList，如果是直接使用原数组questionList，就会导致react没有检测到数组改变就会导致页面不更新
        const updatedList = leftTitle.map(everyOne => {
            if (everyOne.index === item.index) {
                return { ...everyOne, active: true };
            } else {
                return { ...everyOne, active: false };
            }
        });
        setLeftTitle(updatedList);
    };
    return (
        <>
            <div className="page-main account testProblemBox">
                <div className="container">
                    <div className="search-bar">
                        <div className="page-title">Test question management</div>
                        <div className="search-bar-right">
                            {questionList.length > 0 ? (
                                isEditFlag ? (
                                    <div className="flex-end">
                                        <div className="grayBtn" onClick={() => editChange()}>
                                            <div>Cancel</div>
                                        </div>
                                        <Button
                                            className="orangeBtn ml-10"
                                            type="primary"
                                            htmlType="submit"
                                            disabled={confirmLoading}
                                            loading={confirmLoading}
                                            onClick={() => confirmChange()}
                                        >
                                            Save
                                        </Button>
                                    </div>
                                ) : (
                                    <Button
                                        className="orangeBtn ml-10"
                                        type="primary"
                                        htmlType="submit"
                                        onClick={() => editChange()}
                                    >
                                        Edit
                                    </Button>
                                )
                            ) : null}
                        </div>
                    </div>
                    <div>
                        <Row gutter={30}>
                            <Col span={3}>
                                <div className="leftContent">
                                    {leftLoading ? (
                                        <div className="flex-center leftLoadingBox">
                                            <Spin tip="Loading" />
                                        </div>
                                    ) : (
                                        leftTitle.map((item, index) => {
                                            return (
                                                <div
                                                    key={index}
                                                    className={item.active ? 'leftItemBox active' : 'leftItemBox'}
                                                    onClick={() => clickItem(item)}
                                                >
                                                    {item.name}
                                                </div>
                                            );
                                        })
                                    )}
                                </div>
                            </Col>
                            <Col span={21}>
                                <div className="rightContent">
                                    {loading ? (
                                        <div className="data_loading flex-center loadingBox">
                                            <Spin tip="Loading" />
                                        </div>
                                    ) : (
                                        <div>
                                            <div className="rightTitle">{currentLeft.name || 'Social Awareness'}</div>

                                            {questionList.length > 0 ? (
                                                questionList.map((item, index) => {
                                                    return (
                                                        <div className="questionContent" key={index}>
                                                            <div className="flex-between">
                                                                <div>
                                                                    {/* {item.question || 'Test Question' + (index * 1 + 1)} */}
                                                                    {'Test Question' + (index * 1 + 1)}
                                                                </div>
                                                                <div
                                                                    className={
                                                                        item.answerScoreAsc
                                                                            ? 'rightBtn flex-left answerActive'
                                                                            : 'rightBtn flex-left answerNoActive'
                                                                    }
                                                                    onClick={() => answerScoreAscChange(item)}
                                                                >
                                                                    <div>Positive sequence</div>
                                                                    <div className="rightIcon">
                                                                        <SwapOutlined />
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div className="textAreaContent">
                                                                <TextArea
                                                                    value={item.questionTextValue}
                                                                    onChange={e =>
                                                                        changeTextValue(e.target.value, index)
                                                                    }
                                                                    placeholder={item.placeholder}
                                                                    autoSize={{ minRows: 3, maxRows: 5 }}
                                                                    disabled={item.disabled}
                                                                />
                                                            </div>
                                                        </div>
                                                    );
                                                })
                                            ) : (
                                                <div className="emptyBox flex-center">
                                                    <Empty description="No data" />
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>
                            </Col>
                        </Row>
                    </div>
                </div>
            </div>
        </>
    );
};

export default TestProblem;
